package com.fm.Utils;

import java.io.*;
import java.util.Properties;

public class Utils {

    // 获取本地文件列表名
    public static StringBuffer getUpLoadFileName() {
        // 指定目录路径
        StringBuffer s = new StringBuffer();
        int i = 1;
        String directoryPath = "src/main/resources/upLoad";
        File folder = new File(directoryPath);
        File[] files = folder.listFiles();              // 获取文件列表
        for (File file : files) {                       // 遍历文件列表
            if (file.isFile()) {                        // 判断是否为普通文件
                s.append(i++).append(". ").append(file.getName()).append("\n");
            }
        }
        return s;
    }

    // 获取Properties值
    public static String getPropertiesFileData(String Key){
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src/main/resources/config.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 读取属性
        return properties.getProperty(Key);
    }



    //输入流
    public static String printInputStreamText(InputStream inputStream) {
        byte[] bytes = new byte[1024];
        int len;
        String s = "";
        while (true) {
            try {
                if ((len = inputStream.read(bytes)) == -1) break;  //里面为空的时候为-1 将读取到的长度给len
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            s += new String(bytes, 0, len);
            System.out.print(s);
        }
        return s;
    }


    //发送 输入流文件
    public static void sendOutputStreamText(OutputStream outputStream, String text) {
        try {
            outputStream.write(text.getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    //
    public static void sendOutputStreamFile(OutputStream outputStream, String FilePath) {
        // 读取本地文件，并通过输出流发送给服务器
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(FilePath);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        byte[] buffer = new byte[1024];
        int bytesRead;

        while (true) {
            try {
                if (!((bytesRead = fileInputStream.read(buffer)) != -1)) break;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                outputStream.write(buffer, 0, bytesRead);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


}
